var webgl_config = {
	"23": {
		name: "发电站",
		lon: "lon",
		lat: "lat",
		legendColumn: "type",
		featurnInfo: [{"flag":"stationName", "name":"站名"},
		              {"flag":"lon", "name":"经度"},
		              {"flag":"lat", "name":"纬度"},
		              {"flag":"type", "name":"类型"}],
		legendType: "img_1",
		legendLevel: "光伏电站,风电站",
		legend: "resources/images/powerStation_1.png;resources/images/powerStation_2.png",
		label: null
	},
	"65": {
		name: "中小河流隐患点",
		lon: "longitude",
		lat: "latitude",
		featurnInfo: [{"flag":"v_HIDDEN_NAME", "name":"名称"},
		              {"flag":"v_TA_PHONE", "name":"联系人"},
		              {"flag":"v_TA_FILLUNIT", "name":"联系电话"},
		              {"flag":"longitude", "name":"经度"},
		              {"flag":"latitude", "name":"纬度"}
		             ],
		legendType: "img",
		legend: "resources/images/hidden_msc.png",
		label: null
	},
	"66": {
		name: "山洪隐患点",
		lon: "longitude",
		lat: "latitude",
		featurnInfo: [{"flag":"v_HIDDEN_NAME", "name":"名称"},
		              {"flag":"v_TA_PREPARER", "name":"联系人"},
		              {"flag":"v_TA_PHONE", "name":"联系电话"},
		              {"flag":"longitude", "name":"经度"},
		              {"flag":"latitude", "name":"纬度"}
		             ],
		legendType: "img",
		legend: "resources/images/hidden_tsf.png",
		label: null
	},	
	"101": {
		ajaxData: {"V_DISA_TYPE": "中小河流"},
		name: "中小河流预警点",
		lon: "longitude",
		lat: "latitude",
		featurnInfo: [{"flag":"v_ALARM_PLACE", "name":"预警点名称"},
		              {"flag":"v_WARNING_LEVEL", "name":"警戒水位(米)"},
		              {"flag":"v_SAFETY_LEVEL", "name":"保证水位(米)"},
		              {"flag":"v_DAM_HIGHT", "name":"堤坝高度(米)"},
		              {"flag":"v_WST_BASE", "name":"基面高度(米)"},
		              {"flag":"v_DF_PAAREA", "name":"影响面积(平方千米)"},
		              {"flag":"v_DF_PAPOP", "name":"影响人口(人)"},
		              {"flag":"v_DF_PAHHOLD", "name":"影响户数(户)"},
		              {"flag":"v_DF_PAASSET", "name":"影响资产(万元)"}
		             ],
		legendType: "img",
		legend: "resources/images/alarms_1.png",
		label: null
	},
	"102": {
		ajaxData: {"V_DISA_TYPE": "山洪"},
		name: "山洪预警点",
		lon: "longitude",
		lat: "latitude",
		featurnInfo: [{"flag":"v_ALARM_PLACE", "name":"预警点名称"},
		              {"flag":"v_DF_PAAREA", "name":"影响面积(平方千米)"},
		              {"flag":"v_DF_PAPOP", "name":"影响人口(人)"},
		              {"flag":"v_DF_PAHHOLD", "name":"影响户数(户)"},
		              {"flag":"v_DF_PAASSET", "name":"影响资产(万元)"}
		             ],
        legendType: "img",
 		legend: "resources/images/alarms_2.png",
 		label: null
	},
	"103": {
		ajaxData: {"V_DISA_TYPE": "泥石流"},
		name: "泥石流预警点",
		lon: "longitude",
		lat: "latitude",
		featurnInfo: [{"flag":"v_ALARM_PLACE", "name":"预警点名称"},
		              {"flag":"v_DF_PAAREA", "name":"影响面积(平方千米)"},
		              {"flag":"v_DF_PAPOP", "name":"影响人口(人)"},
		              {"flag":"v_DF_PAHHOLD", "name":"影响户数(户)"},
		              {"flag":"v_DF_PAASSET", "name":"影响资产(万元)"}
		             ],
        legendType: "img",
 		legend: "resources/images/alarms_3.png",
 		label: null
	},
	"104": {
		ajaxData: {"V_DISA_TYPE": "滑坡"},
		name: "滑坡预警点",
		lon: "longitude",
		lat: "latitude",
		featurnInfo: [{"flag":"v_ALARM_PLACE", "name":"预警点名称"},
		              {"flag":"v_DF_PAAREA", "name":"影响面积(平方千米)"},
		              {"flag":"v_DF_PAPOP", "name":"影响人口(人)"},
		              {"flag":"v_DF_PAHHOLD", "name":"影响户数(户)"},
		              {"flag":"v_DF_PAASSET", "name":"影响资产(万元)"}
		             ],
        legendType: "img",
 		legend: "resources/images/alarms_4.png",
 		label: null
	}
};

var handlerLine = null;
var handlerDis = null;
var handlerArea = null;
var handlerHeight = null;
var tooltip = createTooltip(document.body);

window.onload = function(){
	initBox();
	initMap();
	eventListen();
};

function clo() {
    $('.tab-content').css('display', 'none');
}

/**
 * @note 页面初始化大小
 * @author 吴义迪
 * @create_time 2017-10-23
 */
function initBox(){
	$("#map").outerWidth($(window).width());
	$("#map").outerHeight($(window).height());
}

/**
 * @note 初始化三维地图
 * @author 吴义迪
 * @create_time 2017-10-23
 */
function initMap(){	
	// 显示区域添加三维球 （底图为高程数据）
	Global.webgl.baseViewer = new Cesium.Viewer(
		'map',{
		terrainProvider  : new Cesium.CesiumTerrainProvider({
			url : Global.common.iserverPath + "/iserver/services/3D-NMGDEM/rest/realspace/datas/nmgdem30@dem",
			isSct : true
		}),
		navigation: true,
		geocoder : true,
		infoBox: true,
		terrainExaggeration: 1.5
	});
	Global.webgl.baseViewer.geocoder.viewModel.geoKey = '79F9yph6kv8c8I9aARQUxtvn';
	//隐藏左下角图层介绍
	$(".cesium-viewer-bottom").hide();
	//加载天地图影像图
	loadTiandituImageLayer();
	//加载天地图影像注记图
	loadTiandituImageTextLayer();
	//定位
	flyTodestination(111.7, 40.8, 100000);
}

/**
 * @note 加载天地图影像图
 * @author 吴义迪
 * @create_time 2017-10-24
 */
function loadTiandituImageLayer(){
//	var imageryProvider = new Cesium.SuperMapImageryProvider({
//		url : Global.common.iserverPath+"/iserver/services/map-tianditu/rest/maps/影像底图_墨卡托"
//	});
//	var imageryLayers = Global.webgl.baseViewer.imageryLayers;
//	var layer = imageryLayers.addImageryProvider(imageryProvider);
	
	var imageryLayers = Global.webgl.baseViewer.imageryLayers;
	var labelImagery = new Cesium.TiandituImageryProvider({
		mapStyle : Cesium.TiandituMapsStyle.CIA
	});
	imageryLayers.addImageryProvider(labelImagery);
}

/**
 * @note 加载天地图影像注记图
 * @author 吴义迪
 * @create_time 2017-10-24
 */
function loadTiandituImageTextLayer(){
//	var imageryProvider = new Cesium.SuperMapImageryProvider({
//		url : Global.common.iserverPath+"/iserver/services/map-tianditu/rest/maps/影像中文注记_墨卡托"
//	});
//	var imageryLayers = Global.webgl.baseViewer.imageryLayers;
//	imageryLayers.addImageryProvider(imageryProvider);
	
	var imageryLayers = Global.webgl.baseViewer.imageryLayers;
	var labelImagery = new Cesium.TiandituImageryProvider({
		mapStyle : Cesium.TiandituMapsStyle.CIA_C
	});
	imageryLayers.addImageryProvider(labelImagery);
}

/**
 * @note 监听事件
 * @author 吴义迪
 * @create_time 2017-10-25
 */
function eventListen(){
	//三维地图上要素点击事件
	var handler = new Cesium.ScreenSpaceEventHandler(Global.webgl.baseViewer.scene.canvas);  
    handler.setInputAction(function (movement) {  
        var pick = Global.webgl.baseViewer.scene.pick(new Cesium.Cartesian2(movement.position.x, movement.position.y));  
        if(Cesium.defined(pick)){  
            if(pick){  
            	
            }
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK); 
    
    //左侧图层列表点击事件
    $("#layer_list").on("click", layerListClickFunc);
    
    $(".box").bind({
        "mouseenter": function () {
            $(this).find("ul").show();
        },
        "mouseleave": function () {
            $(this).find("ul").hide();
        },
        "click": function (event) {
            if (event.target.tagName == "A") {
                $(this).find("input").val($(event.target).text()); //传具体的文字
            }
            $(this).find("ul").hide();
        }
    });
    
    $(".aaa").click(function () {
        $('.tab-content').css('display', 'block');
    });

    $(".tool-img-o").click(function () {
        $(".tool-con").css("display","block");
        $(".tool-img-o").css("display","none");
        $(".tool-img-c").css("display","block");
    });
    $(".tool-img-c").click(function () {
        $(".tool-con").css("display","none");
        $(".tool-img-c").css("display","none");
        $(".tool-img-o").css("display","block");
    });
    
    /**
     * @note 绘制线-控件
     * @author 吴义迪
     * @create_time 2017-11-23
     */
    handlerLine = new Cesium.DrawHandler(Global.webgl.baseViewer,Cesium.DrawMode.Line);
    handlerLine.activeEvt.addEventListener(function(isActive){
    	if(isActive == true){
    		Global.webgl.baseViewer.enableCursorStyle = false;
    		Global.webgl.baseViewer._element.style.cursor = '';
    		$('body').removeClass('drawCur').addClass('drawCur');
    	}
    	else{
    		Global.webgl.baseViewer.enableCursorStyle = true;
    		$('body').removeClass('drawCur');
    	}
    });
//    handlerLine.movingEvt.addEventListener(function(windowPosition){
//    	if(handlerLine.isDrawing){
//    		tooltip.showAt(windowPosition,'<p>左键点击确定折线中间点</p><p>右键单击结束绘制</p>');
//    	}
//    	else{
//    		tooltip.showAt(windowPosition,'<p>点击绘制第一个点</p>');
//    	}
//    });
    handlerLine.drawEvt.addEventListener(function(result){
    	tooltip.setVisible(false);
    });
    
    //初始化测量距离
    handlerDis = new Cesium.MeasureHandler(Global.webgl.baseViewer,Cesium.MeasureMode.Distance,1);
    //注册测距功能事件
    handlerDis.measureEvt.addEventListener(function(result){
	    var distance = result.distance > 1000 ? (result.distance/1000) + 'km' : result.distance + 'm';
	    handlerDis.disLabel.text = '距离:' + distance;
	    handlerDis.disLabel.outlineColor = new Cesium.Color(0, 0, 1);
	    handlerDis.disLabel.font='100 20px sans-serif';
	    handlerDis.disLabel.outlineWidth=5;
    });
    handlerDis.activeEvt.addEventListener(function(isActive){
	    if(isActive == true){
	    	Global.webgl.baseViewer.enableCursorStyle = false;
	    	Global.webgl.baseViewer._element.style.cursor = '';
		    $('body').removeClass('measureCur').addClass('measureCur');
	    }
	    else{
	    	Global.webgl.baseViewer.enableCursorStyle = true;
		    $('body').removeClass('measureCur');
	    }
    });
    

    //初始化测量面积
    handlerArea = new Cesium.MeasureHandler(Global.webgl.baseViewer,Cesium.MeasureMode.Area,1);
    handlerArea.measureEvt.addEventListener(function(result){
    	var area = result.area > 1000000 ? result.area/1000000 + 'km²' : result.area + '㎡';
    	handlerArea.areaLabel.text = '面积:' + area;
    	handlerArea.areaLabel.outlineColor = new Cesium.Color(0, 0, 1);
    	handlerArea.areaLabel.font='100 20px sans-serif';
    	handlerArea.areaLabel.outlineWidth=5.0;
    });
    handlerArea.activeEvt.addEventListener(function(isActive){
    	if(isActive == true){
    		Global.webgl.baseViewer.enableCursorStyle = false;
    		Global.webgl.baseViewer._element.style.cursor = '';
    		$('body').removeClass('measureCur').addClass('measureCur');
    	}
    	else{
    		Global.webgl.baseViewer.enableCursorStyle = true;
    		$('body').removeClass('measureCur');
    	}
    });
    
    //初始化测量高度
    handlerHeight = new Cesium.MeasureHandler(Global.webgl.baseViewer,Cesium.MeasureMode.DVH);
    handlerHeight.measureEvt.addEventListener(function(result){
	    var distance = result.distance > 1000 ? (result.distance/1000).toFixed(2) + 'km' : result.distance + 'm';
	    var vHeight = result.verticalHeight > 1000 ? (result.verticalHeight/1000*1.5).toFixed(2) + 'km' : result.verticalHeight/1.5.toFixed(2) + 'm';
	    var hDistance = result.horizontalDistance > 1000 ? (result.horizontalDistance/1000).toFixed(2) + 'km' : result.horizontalDistance + 'm';
	    handlerHeight.disLabel.text = '空间距离:' + distance;
	    handlerHeight.disLabel.outlineColor = new Cesium.Color(0, 0, 1);
	    handlerHeight.disLabel.font='100 20px sans-serif';
	    handlerHeight.disLabel.outlineWidth=5.0;
	    handlerHeight.vLabel.text = '垂直高度:' + vHeight;
	    handlerHeight.vLabel.outlineColor = new Cesium.Color(0, 0, 1);
	    handlerHeight.vLabel.font='100 20px sans-serif';
	    handlerHeight.vLabel.outlineWidth=5.0;
	    handlerHeight.hLabel.text = '水平距离:' + hDistance;
	    handlerHeight.hLabel.outlineColor = new Cesium.Color(0, 0, 1);
	    handlerHeight.hLabel.font='100 20px sans-serif';
	    handlerHeight.hLabel.outlineWidth=5.0;
    });
    handlerHeight.activeEvt.addEventListener(function(isActive){
	    if(isActive == true){
	    	Global.webgl.baseViewer.enableCursorStyle = false;
	    	Global.webgl.baseViewer._element.style.cursor = '';
		    $('body').removeClass('measureCur').addClass('measureCur');
	    }else{
	    	Global.webgl.baseViewer.enableCursorStyle = true;
		    $('body').removeClass('measureCur');
	    }
    });
  
    /**
     * @note 工具栏点击事件
     * @author 吴义迪
     * @create_time 2017-11-23
     */
    $("#tool").click(function(e){
    	if($(e.target).attr("id") == "tool_draw"){
    		deactiveAll();
    		handlerLine && handlerLine.activate();
    	}else if($(e.target).attr("id") == "tool_dis"){
    		deactiveAll();
    		handlerDis && handlerDis.activate();
    	}else if($(e.target).attr("id") == "tool_area"){
    		deactiveAll();
    		handlerArea && handlerArea.activate();
    	}else if($(e.target).attr("id") == "tool_high"){
    		deactiveAll();
    		handlerHeight && handlerHeight.activate();
    	}else if($(e.target).attr("id") == "tool_clear"){
    		clearAll();    	
    	}
    });
}

/**
 * @note 定位至目的地，通过经纬度坐标
 * @author 吴义迪
 * @create_time 2017-10-24
 */
function flyTodestination(x, y, z){
	var camera = new Cesium.Camera(Global.webgl.baseViewer.scene);
	camera.flyTo({
		destination: Cesium.Cartesian3.fromDegrees(x, y, z),
	});
}

function flyToLayer(layer){
	var camera = new Cesium.Camera(Global.webgl.baseViewer.scene);
	camera.flyTo(layer);
}

/**
 * @note 请求基本点图数据
 * @author 吴义迪
 * @create_time 2017-10-25
 */
function requestBasePointLayer(id, url){
	var data = {};
	if(webgl_config[id].ajaxData != null){
		data = webgl_config[id].ajaxData;
	}
	$.ajax({
		url: url,
		type: "post",
		data: data,
		dataType: "json",
		//回调函数
		success:function(result){
			if(result.status == 0){
				showBasePointLayer(id, result.data);
			}
		},
		error:function(){
			//异常处理
			window.console.log("请求基本点图数据异常");
		}
	});
}

/**
 * @note 展示基本点图数据
 * @author 吴义迪
 * @create_time 2017-10-25
 */
function showBasePointLayer(id, value){
	var dataSource = new Cesium.CustomDataSource("layer_"+id+"");
	for(var i=0; i<value.length; i++){
		if(isNaN(value[i][webgl_config[id].lon]) == true || isNaN(value[i][webgl_config[id].lat]) == true){
			continue;
		}
		var description = "<table style=\"box-shadow:none\">";
		for(var j=0; j<webgl_config[id].featurnInfo.length; j++){
			if(value[i][webgl_config[id].featurnInfo[j].flag] != null){
				description += "<tr class=\"popup_tr\">" +
							   "	<td style=\"padding:2px 0;\">"+webgl_config[id].featurnInfo[j].name+"：</td>" +
							   "	<td style=\"padding:2px 0;\">"+value[i][webgl_config[id].featurnInfo[j].flag]+"</td>" +
							   "</tr>";
			}
		}
		description += "</table>";
		var entity = {
			id: id + "_" + i,
			name: webgl_config[id].name,
			position: Cesium.Cartesian3.fromDegrees(value[i][webgl_config[id].lon], value[i][webgl_config[id].lat], 10000),
			description: description,
		    data: value[i]	
		};
		if(webgl_config[id].label != null){
			entity.label = {
		        text : value[i][webgl_config[id].label],  
		        font : '14px Microsoft Yahei',  
		        style : Cesium.LabelStyle.FILL_AND_OUTLINE,  
		        fillColor: new Cesium.Color(1,1,1,1),
		        outlineColor: new Cesium.Color(0,0,0,1),
		        outlineWidth: 3,
		        verticalOrigin : Cesium.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置  
		        pixelOffset : new Cesium.Cartesian2( 0, -9 )   //偏移量  
		    };
		}
		if(webgl_config[id].legendType == "img"){
			entity.billboard = {
		        image : webgl_config[id].legend,  
		        width : 24,  
		        height : 24  
		    }; 
		}else if(webgl_config[id].legendType == "img_1"){
			for(var k=0; k<webgl_config[id].legendLevel.length; k++){
				if(value[i][webgl_config[id].legendColumn] != null && value[i][webgl_config[id].legendColumn] == webgl_config[id].legendLevel.split(",")[k]){
					entity.billboard = {
				        image : webgl_config[id].legend.split(";")[k],  
				        width : 24,  
				        height : 24  
				    }; 
					break;
				}
			}
		}
		dataSource.entities.add(entity);
	}
	Global.webgl.baseViewer.dataSources.add(dataSource);
}

/**
 * @note 展示rest请求图层
 * @author 吴义迪
 * @create_time 2017-10-25
 */
function showRestLayer(id, url){
	var imageryProvider = new Cesium.SuperMapImageryProvider({
		url : url
	});
	imageryProvider.name = "test";
	var imageryLayers = Global.webgl.baseViewer.imageryLayers;
	var layer = imageryLayers.addImageryProvider(imageryProvider);
	if(webgl_config["layer_"+id+""] == null){
		webgl_config["layer_"+id+""] = {};
		webgl_config["layer_"+id+""].layer = layer;
	}else{
		webgl_config["layer_"+id+""].layer = layer;
	}
	Global.webgl.baseViewer.flyTo(layer);
}

/**
 * @note 图层列表点击事件
 * @author 吴义迪
 * @create_time 2017-10-26
 */
function layerListClickFunc(e){
	e = e || window.event;
	if(e.target.attributes.layerid){
		var id = e.target.attributes.layerid.nodeValue;
		//打开图层
		if(e.target.attributes.flag.nodeValue == "0"){
			e.target.attributes.flag.nodeValue = "1";
			$(e.target).css({"color":"#139eff", "background":"rgba(20, 48, 60, .6)"});
			loadLayer(id);
		}
		//关闭图层
		else{
			e.target.attributes.flag.nodeValue = "0";
			$(e.target).css({"color":"", "background":""});
			closeLayer(id);
		}
	}
}

/**
 * @note 打开图层
 * @author 吴义迪
 * @create_time 2017-10-26
 */
function loadLayer(id){
	if(id == "23" || id == "65" || id == "66" || id == "101" || id == "102" || id == "103" || id == "104"){
		requestBasePointLayer(id, Global.common.ajaxPath + $("#layer_"+id+"").attr("url"));
	}else if(id == "76" || id == "110"){
		showRestLayer(id, Global.common.iserverPath + $("#layer_"+id+"").attr("url"));
	}
}

/**
 * @note 关闭图层
 * @author 吴义迪
 * @create_time 2017-10-25
 */
function closeLayer(id){
	//清除点图层
	for(var i=0; i<Global.webgl.baseViewer.dataSources.length; i++){
		if(Global.webgl.baseViewer.dataSources.get(i).name == "layer_"+id+""){
			Global.webgl.baseViewer.dataSources.remove(Global.webgl.baseViewer.dataSources.get(i), true); 
		}
	}
	//清除图像图层
	if(webgl_config["layer_"+id+""].layer != null){
		Global.webgl.baseViewer.imageryLayers.remove(webgl_config["layer_"+id+""].layer, true);
		webgl_config["layer_"+id+""].layer = null;
	}
}

/**
 * @note 控件关闭
 * @author 吴义迪
 * @create_time 2017-11-23
 */
function deactiveAll(){
	handlerLine && handlerLine.deactivate();
	handlerDis && handlerDis.deactivate();
	handlerArea && handlerArea.deactivate();
	handlerHeight && handlerHeight.deactivate();
}

/**
 * @note 控件清除
 * @author 吴义迪
 * @create_time 2017-11-23
 */
function clearAll(){
	handlerLine && handlerLine.clear();
	handlerDis && handlerDis.clear();
	handlerArea && handlerArea.clear();
	handlerHeight && handlerHeight.clear();
}

function createTooltip(frameDiv) {

    var tooltip = function(frameDiv) {

        var div = document.createElement('DIV');
        div.className = "twipsy right";

        var arrow = document.createElement('DIV');
        arrow.className = "twipsy-arrow";
        div.appendChild(arrow);

        var title = document.createElement('DIV');
        title.className = "twipsy-inner";
        div.appendChild(title);

        this._div = div;
        this._title = title;
        this.message = '';

        // add to frame div and display coordinates
        frameDiv.appendChild(div);
        var that = this;
        div.onmousemove = function(evt){
            that.showAt({x : evt.clientX,y : evt.clientY},that.message);
        };
    };

    tooltip.prototype.setVisible = function(visible) {
        this._div.style.display = visible ? 'block' : 'none';
    };

    tooltip.prototype.showAt = function(position, message) {
        if(position && message) {
            this.setVisible(true);
            this._title.innerHTML = message;
            this._div.style.left = position.x + 10 + "px";
            this._div.style.top = (position.y - this._div.clientHeight / 2) + "px";
            this.message = message;
        }
    };

    return new tooltip(frameDiv);
}